package cn.cimoc.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @author LGZ
 * @date 2021/10/20 21:11
 * <p>
 * jwt工具类
 */
public class JwtUtils {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    /**
     * 密钥
     */
    private static final String SECRET = "ju!aSWWd23@4";
    private static final String ISS = "lgz";

    /**
     * <p>
     * @param map : 写入payload中的数据
     * @return : token
     */
    public static String getToken(Map<String, String> map) {
        // 默认7天
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);

        // payload
        JWTCreator.Builder tokenBuilder = JWT.create();
        map.forEach(tokenBuilder::withClaim);

        tokenBuilder
                .withExpiresAt(instance.getTime())
                .withIssuer(ISS);
        return tokenBuilder.sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * <p>
     * @param map : 写入payload中的数据
     * @param day : token过期天数
     * @return : token
     */
    public static String getToken(Map<String, String> map, int day) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, day);

        // payload
        JWTCreator.Builder tokenBuilder = JWT.create();
        map.forEach(tokenBuilder::withClaim);

        tokenBuilder
                .withExpiresAt(instance.getTime())
                .withIssuer(ISS);
        return tokenBuilder.sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * <p>
     * 获取token信息
     * @param token :
     * @return : token信息
     * @exception JWTVerificationException token无效时抛出
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
    }

    /**
     * <p>
     * 判断token是否已过期
     * @param token token
     * @return 过期返回true
     */
    public static boolean isExpiration(String token) {
        try {
            return verify(token).getExpiresAt().before(new Date());
        } catch (JWTVerificationException e) {
            return true;
        }
    }
}
